package com.zone.gateway.core.socket.agreement;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.netty.handler.codec.http.*;

/**
 * @author: zongzi
 * @description: 返回值解析器
 * @date: 2025/4/22
 */
public class ResponseParser {


    /**
     * 创建响应
     *
     * @return HTTP响应对象
     */
    public static DefaultFullHttpResponse createResponse(GatewayResultMessage result) {
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

        // 写入返回信息
        response.content().writeBytes(JSONObject.toJSONBytes(result, SerializerFeature.PrettyFormat));
        // 设置头部信息
        HttpHeaders headers = response.headers();
        // 内容类型
        headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + "; charset=UTF-8");
        // 内容长度
        headers.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        // 持久连接
        headers.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        // 跨域配置
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "*");
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE");
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        return response;
    }
}
